package com.ming_za.od_updater_sdk.processing.search;

import com.ming_za.od_updater_sdk.IUpdater;
import com.ming_za.od_updater_sdk.processing.record.IUpdateRecorder;
import com.ming_za.od_updater_sdk.server_api.ServerAPIState;
import com.ming_za.od_updater_sdk.server_api.IUpdaterServer;
import com.ming_za.od_updater_sdk.server_api.result_obj.data.ResData;
import com.ming_za.od_updater_sdk.exception.UnConnectServerException;
import com.ming_za.od_updater_sdk.obj.ReqValue;
import com.ming_za.od_updater_sdk.obj.Res;
import com.ming_za.od_updater_sdk.obj.UpdateRecord;

import java.util.*;

/**
 * 智能资源检索
 * <p>从需要更新的资源中智能匹配最新资源，以免不必要的更新操作</p>
 */
public class IntelligentSearchProcessor implements IResSearchProcessor {

    @Override
    public void getUpdateRes(Map<Integer, List<Res>> needRes, IUpdater odUpdater, UpdateRecord updateRecord) {

        IUpdaterServer updaterServerAPI = odUpdater.getUpdaterServerAPI();

        ReqValue<Integer[]> reqValue = updaterServerAPI.getVersions(updateRecord.getVersion(), odUpdater.getUnpublishKey(),odUpdater);
        if (reqValue.getServerAPIState() != ServerAPIState.SUCCESS){
            throw new UnConnectServerException("无法连接至服务器");
        }
        Integer[] version = reqValue.getValue();

        if (version == null || version.length < 1){
            return;
        }

        //从最新版到旧版排序
        Arrays.sort(version, Comparator.reverseOrder());

        //用于去除不同版本中相同路径的资源，以最新版为基
        Set<String> existPath = new HashSet<>();

        for (int v:version){
            if (v == updateRecord.getVersion()){
                continue;
            }
            ReqValue<ResData[]> versionRes = updaterServerAPI.getVersionRes(v, odUpdater.getLabelId(), odUpdater.getUnpublishKey(),odUpdater);

            if (versionRes.getServerAPIState() != ServerAPIState.SUCCESS){
                throw new UnConnectServerException("无法连接至服务器");
            }

            //当检索的版本是记录中的未完成版本时，将取出未完成版本中完成的资源进行对比排除
            Set<Long> completedRes = updateRecord.getNotCompletedVersion() == v? updateRecord.getResId() : new HashSet<>();

            List<Res> resList = new ArrayList<>();
            for (ResData r : versionRes.getValue()){
                if (!existPath.contains(r.getPath()) && !completedRes.contains(r.getResId())){
                    //筛选出需要更新的内容
                    String path = r.getPath();
                    resList.add(new Res(r.getResId(),path,r.isDelete()));
                    existPath.add(path);
                }
            }
            if (!resList.isEmpty()){
                needRes.put(v, resList);
            }
        }

        if (existPath.isEmpty()){
            IUpdateRecorder updateRecorder = odUpdater.getUpdateRecorder();
            updateRecorder.useVersion(odUpdater,version[0]);
            updateRecorder.complete();
        }
    }
}
